package com.hava.datasource;

import org.apache.commons.dbcp2.BasicDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by yanfa on 2016/9/24.
 */
public class DBPool {

    public static BasicDataSource basicDataSource = null;

    public final static String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    public final static String DB_URL = "jdbc:mysql://192.168.1.200/test";
    public final static String USER = "root";
    public final static String PASSWORD = "dVHJtG0T:pf*";

    public void init()
    {
        basicDataSource = new BasicDataSource();
        basicDataSource.setUrl(DB_URL);
        basicDataSource.setDriverClassName(JDBC_DRIVER);
        basicDataSource.setUsername(USER);
        basicDataSource.setPassword(PASSWORD);
    }

    public void test()
    {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            connection = basicDataSource.getConnection();

//            statement = connection.createStatement();
            resultSet = statement.executeQuery("SELECT * FROM product");

            while(resultSet.next())
            {
                Integer index = resultSet.getRow();
                Integer Id = resultSet.getInt("Id");
                String ProductName = resultSet.getString("ProductName");
                Integer Inventory = resultSet.getInt("Inventory");
                System.out.println("resultSet [row]:" + index + " [product.Id]:" + Id + " [product.ProductName]:" + ProductName + " [product.Inventory]:" + Inventory);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            try {
                resultSet.close();
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }
}
